import React, { useEffect, useMemo, useRef, useState } from "react";
import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { AtImagePicker } from "taro-ui";
import "./index.scss";
import {
  ImageUploaderProps,
  FileModel
} from "../../../types/components/image-uploader";
import { uploadToOss } from "../../utils";

/**
 * ImageUploader 图片选择
 */
const ImageUploader: React.FC<ImageUploaderProps> = ({
  defaultUris = "",
  length = 3,
  disabled,
  onChange,
  count = 9,
  securitySignApi,
  apiData,
  ossConfig,
  ...otherProps
}) => {
  const [urls, setUrls] = useState<string>(defaultUris);
  const onChangeCallRef = useRef(onChange);
  const callableRef = useRef(false);

  useEffect(() => {
    onChangeCallRef.current = onChange;
  });

  useEffect(() => {
    setUrls(defaultUris);
    return () => {
      Taro.hideLoading();
    };
  }, [defaultUris]);

  useEffect(() => {
    if (callableRef.current) {
      onChangeCallRef.current && onChangeCallRef.current(urls);
    }
  }, [urls]);

  const files = useMemo(() => {
    if (!urls) {
      return [];
    }
    return urls.split(",").map(url => {
      return {
        url,
        file: {
          path: url,
          size: 0
        }
      };
    });
  }, [urls]) as FileModel[];

  // 剩余的可以选择的数量
  const remainingQuantity = count - files.length;
  const onChangeImage = async function(file, operationType, index: number) {
    
    callableRef.current = true;
    let ps: string[] = urls ? urls.split(",") : [];
    let filesList = file.slice(count - remainingQuantity);

    if (filesList.length > remainingQuantity) {
      filesList = filesList.slice(0, remainingQuantity);
    }
    if (operationType === "add") {
      Taro.showLoading({
        title: "图片上传中..."
      });
      for (let i = 0; i < filesList.length; i++) {
        try {
          let resUpload = await uploadToOss(filesList[i].url, securitySignApi, apiData, ossConfig);
          if (resUpload) {
            ps.push(resUpload as string);
            setUrls(ps.join(","));
          }
        } catch (error) {
          console.log('error', error);
          
        }
       
      }
      Taro.hideLoading();
    } else if (operationType === "remove") {
      setTimeout(() => {
        ps?.splice(index, 1);
        setUrls(ps.join(","));
      }, 0);
    }
  };

  return (
    <View>
      <AtImagePicker
        {...otherProps}
        length={length}
        files={files}
        showAddBtn={files.length < count && !disabled}
        count={count - files.length}
        onImageClick={(file: any) => {
          Taro.previewImage({
            current: file.url,
            urls: urls ? urls.split(",") : []
          });
        }}
        onChange={onChangeImage}
      ></AtImagePicker>
    </View>
  );
};

export default ImageUploader;
